/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: AccountActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.account.adapter.TagAdapter;
import io.bhex.app.account.event.LocaleChangeEvent;
import io.bhex.app.account.presenter.AccountPresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.utils.BasicFunctionsUtil;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.CustomerServiceUtils;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.utils.StatusBarExtUtil;
import io.bhex.app.view.TopBar;
import io.bhex.app.web.ui.WebActivity;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.sdk.Urls;
import io.bhex.sdk.account.EventLogin;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.account.bean.UserLevelInfoResponse;
import io.bhex.sdk.config.bean.BasicFunctionsConfig;
import io.bhex.sdk.data_manager.AssetUtilsManager;
import io.bhex.sdk.data_manager.RateDataManager;
import io.bhex.sdk.trade.bean.AllAssetResponse;

/**
 * ================================================
 * 描   述：账户
 * ================================================
 */

public class AccountActivity extends BaseActivity<AccountPresenter, AccountPresenter.AccountUI> implements AccountPresenter.AccountUI, View.OnClickListener , AssetUtilsManager.AssetChangeInterface , CompoundButton.OnCheckedChangeListener{
    private UserInfoBean userInfo;
    private AllAssetResponse mAllAssetResponse;
    private TopBar topBar;
    private BasicFunctionsConfig basicFunctionsConfig;
    private RecyclerView tagRV;
    private TagAdapter tagAdapter;
    private boolean isSkinBlackMode;
    private CheckBox skinSwitch;
    private boolean isAutoSetBlackMode=false;   //页面进入初始化时自动设置标识
    private boolean isUserLevel =false;

    @Override
    protected AccountPresenter.AccountUI getUI() {
        return this;
    }

    @Override
    protected AccountPresenter createPresenter() {
        return new AccountPresenter();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getContentView() {
        return R.layout.fragment_account_layout;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void initView() {
        super.initView();
        isSkinBlackMode = SPEx.get(AppData.SPKEY.SKIN_IS_BLACK_MODE, false);
        skinSwitch = viewFinder.find(R.id.setting_switch_skin);
        isAutoSetBlackMode = true;
        skinSwitch.setChecked(isSkinBlackMode);
        isAutoSetBlackMode = false;

        basicFunctionsConfig = BasicFunctionsUtil.getBasicFunctionsConfig();
        viewFinder.find(R.id.goExchange).setVisibility((basicFunctionsConfig.isFuture() && basicFunctionsConfig.isOption())?View.GONE:View.VISIBLE);
        viewFinder.find(R.id.account_card_voucher_rela).setVisibility(basicFunctionsConfig.isCoupon()?View.GONE:View.VISIBLE);
//        viewFinder.find(R.id.account_point_divider).setVisibility(basicFunctionsConfig.isPointcard()?View.GONE:View.VISIBLE);
//        viewFinder.find(R.id.account_point_rela).setVisibility(basicFunctionsConfig.isPointcard()?View.GONE:View.VISIBLE);
        viewFinder.find(R.id.account_invite_rela).setVisibility(basicFunctionsConfig.isInvite()?View.GONE:View.VISIBLE);
        viewFinder.find(R.id.account_invite_rela_divider).setVisibility(basicFunctionsConfig.isInvite()?View.GONE:View.VISIBLE);
        viewFinder.find(R.id.account_help_rela).setVisibility(basicFunctionsConfig.isCustomer_work_order()?View.GONE:View.VISIBLE);
        viewFinder.find(R.id.account_help_rela_divider).setVisibility(basicFunctionsConfig.isCustomer_work_order()?View.GONE:View.VISIBLE);
        viewFinder.find(R.id.account_report_rela).setVisibility(basicFunctionsConfig.isNovice()?View.GONE:View.VISIBLE);
        viewFinder.find(R.id.account_report_rela_divider).setVisibility(basicFunctionsConfig.isNovice()?View.GONE:View.VISIBLE);
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        topBar.setRightTextMargin(0,PixelUtils.dp2px(16));
        topBar.setRightTextAppearance(this,R.style.BodyL_Dark_Bold);
        topBar.setRightText(getResources().getString(R.string.string_set));
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.goSettings(AccountActivity.this);
            }
        });
        ImageView avatorImg = viewFinder.imageView(R.id.account_avator);
        if (CommonUtil.isBhex(this)) {
            avatorImg.setImageResource(R.mipmap.icon_avator);
        }else{
            avatorImg.setImageResource(R.mipmap.icon_avator_default);
        }
        mAllAssetResponse = AssetUtilsManager.GetInstance().GetAllAsset();

        tagRV = viewFinder.find(R.id.tagRV);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        tagRV.setLayoutManager(linearLayoutManager);
    }

    @Override
    public void onResume() {
        super.onResume();

        if (UserInfo.isLogin()) {
            userInfo = UserInfo.getUserInfo();
            updateUI(userInfo);
        }else{
            resetUnloginStatus();
            viewFinder.find(R.id.account_grade).setVisibility(View.GONE);
        }

        AssetUtilsManager.GetInstance().AddAssetObserver(this);

    }

    private void updateUI(UserInfoBean userInfo) {
        if (userInfo != null) {
            viewFinder.find(R.id.uid_copy).setVisibility(View.VISIBLE);
            int registerType = userInfo.getRegisterType();
            if (registerType==1) {
                viewFinder.textView(R.id.accountName).setText(userInfo.getMobile());
            }else{
                viewFinder.textView(R.id.accountName).setText(userInfo.getEmail());
            }
            viewFinder.textView(R.id.accountUid).setText(getString(R.string.string_format_uid,userInfo.getUserId()));
            viewFinder.textView(R.id.accountUid).setTextIsSelectable(true);

//                int verifyStatus = userInfo.getVerifyStatus();
//                switch (verifyStatus){
//                    case 0:
//                        viewFinder.textView(R.id.account_auth_status).setText(getString(R.string.string_auth_status_no_auth));
//                        break;
//                    case 1:
//                        viewFinder.textView(R.id.account_auth_status).setText(getString(R.string.string_auth_status_check));
//                        break;
//                    case 2:
//                        viewFinder.textView(R.id.account_auth_status).setText(getString(R.string.string_auth_status_check_success));
//                        break;
//                    case 3:
//                        viewFinder.textView(R.id.account_auth_status).setText(getString(R.string.string_auth_status_check_failed));
//                        break;
//                }

            List<UserInfoBean.CustomLabelListBean> customLabelList = userInfo.getCustomLabelList();
            if (customLabelList != null) {
                viewFinder.find(R.id.tagRV).setVisibility(View.VISIBLE);
                setTagRvAdapter(customLabelList);
            }
        }
    }


    @Override
    public void updateUserLevelInfo(UserLevelInfoResponse data) {
        if (UserInfo.isLogin()) {
            UserLevelInfoResponse.UserLevelInfoBean bean =data.getUserLevelInfo();
            if (isUserLevel &&bean!=null &&bean.getLevelConfigIds()!=null &&bean.getLevelConfigIds().size()>0) {
                String levelId =bean.getLevelConfigIds().get(0);
                if ( data.getLevelConfigs()!=null) {
                    for (UserLevelInfoResponse.LevelConfigsBean configsBean : data.getLevelConfigs()) {
                        if (configsBean.getConfigId().equals(levelId)) {
                            // 用户等级
                            viewFinder.find(R.id.account_grade).setVisibility(View.VISIBLE);
                            viewFinder.textView(R.id.account_grade).setText(configsBean.getLevelName());
                            return;
                        }
                    }
                }
            }

            viewFinder.find(R.id.account_grade).setVisibility(View.GONE);
        }
    }

    @Override
    public void updateUserLevelVisible(boolean userLevel) {
        isUserLevel = userLevel;
        viewFinder.find(R.id.account_grade_rela_divider).setVisibility(userLevel?View.VISIBLE:View.GONE);
        viewFinder.find(R.id.account_grade_rela).setVisibility(userLevel?View.VISIBLE:View.GONE);
    }

    private void setTagRvAdapter(List<UserInfoBean.CustomLabelListBean> customLabelList) {
        if (tagAdapter == null) {
            tagAdapter = new TagAdapter(customLabelList);
            tagRV.setAdapter(tagAdapter);

        }else{
            tagAdapter.setNewData(customLabelList);
        }
    }

    @Override
    public void showUserInfo(UserInfoBean data) {
        if (data != null) {
            userInfo = data;
            updateUI(userInfo);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        AssetUtilsManager.GetInstance().removeAssetObserver(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onMessageEvent(EventLogin eventLogin) {
        resetUnloginStatus();
    }

    /**
     * 重置未登录状态
     */
    public void resetUnloginStatus() {
        viewFinder.textView(R.id.accountName).setText(getString(R.string.string_login));
        viewFinder.textView(R.id.accountUid).setText(getString(R.string.string_welcome_bhex,getString(R.string.app_name)));
        viewFinder.textView(R.id.account_order_num).setText("");
        viewFinder.find(R.id.uid_copy).setVisibility(View.GONE);
        viewFinder.find(R.id.tagRV).setVisibility(View.GONE);
    }

    @Override
    public void showPointView(boolean isVisible) {
        viewFinder.find(R.id.account_point_divider).setVisibility(isVisible?View.VISIBLE:View.GONE);
        viewFinder.find(R.id.account_point_rela).setVisibility(isVisible?View.VISIBLE:View.GONE);
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.account_user_rela).setOnClickListener(this);
        viewFinder.find(R.id.accountUid).setOnClickListener(this);
        viewFinder.find(R.id.uid_copy).setOnClickListener(this);
        viewFinder.find(R.id.account_auth_rela).setOnClickListener(this);
        viewFinder.find(R.id.account_card_voucher_rela).setOnClickListener(this);
        viewFinder.find(R.id.account_order_rela).setOnClickListener(this);
        viewFinder.find(R.id.account_security_rela).setOnClickListener(this);
        viewFinder.find(R.id.account_coin_adderss_rela).setOnClickListener(this);
        viewFinder.find(R.id.account_about_us_rela).setOnClickListener(this);
        viewFinder.find(R.id.account_announce_rela).setOnClickListener(this);
        viewFinder.find(R.id.account_help_rela).setOnClickListener(this);
        viewFinder.find(R.id.account_report_rela).setOnClickListener(this);
        viewFinder.find(R.id.account_invite_rela).setOnClickListener(this);
        viewFinder.find(R.id.account_point_rela).setOnClickListener(this);
        viewFinder.find(R.id.deposit).setOnClickListener(this);
        viewFinder.find(R.id.withdraw).setOnClickListener(this);
        viewFinder.find(R.id.goExchange).setOnClickListener(this);
        viewFinder.find(R.id.account_grade_rela).setOnClickListener(this);

        skinSwitch.setOnCheckedChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.accountUid:
            case R.id.uid_copy:
                if (UserInfo.isLogin()) {
                    CommonUtil.copyText(this,UserInfo.getUserId());
                }
                break;
            case R.id.deposit:
                if (UserInfo.isLogin(this, AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                    IntentUtils.goTokenList(this,true);
                }
                break;

            case R.id.account_grade_rela:
                WebActivity.runActivity(this,"",Urls.H5_URL_USER_LEVEL);
                break;
            case R.id.withdraw:
                if (UserInfo.isLogin(this, AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                    IntentUtils.goTokenList(this,false);
                }
                break;
            case R.id.goExchange:
                if (UserInfo.isLogin(this, AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                    IntentUtils.goAssetTransfer(this, "");
                }
                break;
            case R.id.account_user_rela:
                if (UserInfo.isLogin(this, AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
//                    if (userInfo != null) {
//                        int verifyStatus = userInfo.getVerifyStatus();
//                        if (verifyStatus==VERIFY_STATUS.VERIFY_NO.getmStatus()) {
//                            IntentUtils.goIdentityAuth(AccountActivity.this);
////                            VerifyUtil.is2FA(this, new VerifyUtil.VerifyListener() {
////                                @Override
////                                public void on2FAVerify(boolean isVerify2FA) {
////                                    if (isVerify2FA) {
////                                        IntentUtils.goIdentityAuth(AccountActivity.this);
////                                    }else{
////                                        //自动提示去2FA
////                                    }
////                                }
////                            });
//                            return;
//                        }else if(verifyStatus==VERIFY_STATUS.VERIFY_CHECK_FAILED.getmStatus()||verifyStatus==VERIFY_STATUS.VERIFY_CHECKING.getmStatus()){
//                            IntentUtils.goAuthStatus(this,verifyStatus,"");
//                            return;
//                        }
//                    }
//                    IntentUtils.goUserInfoPage(this);
                }
                break;
            case R.id.account_card_voucher_rela:
                //卡券
                if (UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                    WebActivity.runActivity(this,getString(R.string.string_card_voucher), Urls.H5_URL_CARD_VOUCHER);
                }
                break;
            case R.id.account_order_rela:
                //订单管理
                if (UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                    IntentUtils.goNewAllOrders(this);
                }
                break;
            case R.id.account_point_rela:
                //我的点卡
                if (UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                    IntentUtils.goPointCard(this);
                }
                break;
            case R.id.account_invite_rela:
                //我的邀请
                if (UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                    IntentUtils.goMyInvitation(this);
                }
                break;
            case R.id.account_auth_rela:
                if (UserInfo.isLogin(this, AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                    if (userInfo != null) {
                        int userType = userInfo.getUserType();
                        if (userType == 2) {//机构用户
                            IntentUtils.goUserInfoPage(this);
                        }else{

                            IntentUtils.goIdentityAuth(AccountActivity.this);

//                            int verifyStatus = userInfo.getVerifyStatus();
//                            if (verifyStatus==VERIFY_STATUS.VERIFY_NO.getmStatus()) {
//                                IntentUtils.goIdentityAuth(AccountActivity.this);
////                            VerifyUtil.is2FA(this, new VerifyUtil.VerifyListener() {
////                                @Override
////                                public void on2FAVerify(boolean isVerify2FA) {
////                                    if (isVerify2FA) {
////                                        IntentUtils.goIdentityAuth(AccountActivity.this);
////                                    }else{
////                                        //自动提示去2FA
////                                    }
////                                }
////                            });
//                                return;
//                            }else if(verifyStatus==VERIFY_STATUS.VERIFY_CHECK_FAILED.getmStatus()||verifyStatus==VERIFY_STATUS.VERIFY_CHECKING.getmStatus()){
//                                IntentUtils.goAuthStatus(this,verifyStatus,"");
//                                return;
//                            }
                        }
                    }
                }
                break;
            case R.id.account_security_rela:
                //安全中心
                if (UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                    IntentUtils.goSecurityCenter(this);
                }

                break;
            case R.id.account_coin_adderss_rela:
                //提币地址
                if (UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                    IntentUtils.goCoinAddress(this);
                }
                break;
            case R.id.account_announce_rela:
                //公告
                IntentUtils.goAnnouncements(this);
                break;

            case R.id.account_help_rela:
                CustomerServiceUtils.goSubmitOrder(this);
                break;
            case R.id.account_report_rela:
                CustomerServiceUtils.goGuide(this);
                break;
//            case R.id.account_about_us_rela:
//                //关于我们
//                WebActivity.runActivity(this, getString(R.string.string_we), AppData.Config.URL_ABOUT_US);
//                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.setting_switch_skin:
                //换肤
                if (!isAutoSetBlackMode) {
                    SPEx.set(AppData.SPKEY.SKIN_IS_SET_BLACK_MODE, true);
                }
                if (isChecked) {
                    //夜间模式
                    CommonUtil.setBlackSkin();

                } else {
                    CommonUtil.clearBlackSkin();
                }
                StatusBarExtUtil.setStatusColor(this,false,true, SkinColorUtil.getWhite(this));


                break;
        }
    }

    @Override
    public void showOrderNum(String num) {
        viewFinder.textView(R.id.account_order_num).setText(num);
    }

    @Override
    public void OnAssetChanged() {
        AllAssetResponse asset = AssetUtilsManager.GetInstance().GetAllAsset();
        if(asset == null)
            return;

        mAllAssetResponse = asset;
//        showAssetView();

    }

    private void showAssetView(){
        if(mAllAssetResponse != null && UserInfo.isLogin()) {
            String legalMoney = RateDataManager.CurRatePrice(mAllAssetResponse.unit, mAllAssetResponse.totalAsset);
            legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
//            viewFinder.textView(R.id.asset_tip).setText("≈" + legalMoney);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeLanguage(LocaleChangeEvent changeEvent){
        misNeedRomve = 0;
        recreate();
    }
}
